<template>
  <div>
    <div class="list-area">
      <div class="setting-area glo-content-area">
        <div class="btns glo-btn-group">
          <Button
            type="primary"
            @click="showCreate"
            v-if="allPermissions.verAddBtn"
          >{{ $t("versionIndex.verAddBtn") }}</Button>
        </div>
        <div class="title">{{ $t("permissionsIndex.UserTit") }}</div>
      </div>
      <div class="glo-search-area">
        <div class="widget-item glo-clear-after">
          <div class="widget-label">{{ $t("permissionsIndex.UserName") }}</div>
          <Input
            v-model="personName"
            :placeholder="$t('permissionsIndex.UserNameSer')"
            search
            :enter-button="$t('devicesIndex.devNumberBtn')"
            @on-search="$_page_update"
          />
        </div>
         <div class="widget-item glo-clear-after">
          <div class="widget-label">{{ $t("permissionsIndex.UserEmailSer") }}</div>
          <Input
            v-model="personEmail"
            :placeholder="$t('permissionsIndex.UserEmailSer')"
            search
            :enter-button="$t('devicesIndex.devNumberBtn')"
            @on-search="$_page_update"
          />
        </div>

      </div>
      <!-- <div class="glo-selection">
        <Alert show-icon>
          已选择 {{ selection.length }} 项
          <a class="glo-selection-clean" @click="handleSelectionAllStatus(false)">清空</a>
        </Alert>
      </div> -->
      <Table
        ref="table"
        class="list"
        :data="list"
        :columns="columns"
        @on-selection-change="handleSelection"
      />
      <Page
        class="glo-content-area glo-pagenation"
        :total="total"
        :pageSize="pageSize"
        show-sizer
        :current="page"
        show-total
        @on-change="$_page_pageChange"
        @on-page-size-change="$_page_pageSizeChange"
      />
    </div>

    <Modal
        class="modalClass"
        v-model="modal1"
        :title="$t('loginIndex.loginPhoneEdit')"
        >
        <Form :model="formItem" v-model="formItem.id" ref="formItem" :label-width="80" :rules="validateRules">
          <FormItem :label="$t('loginIndex.loginPhoneAccount')" >
              <div>{{passName}}</div>
          </FormItem>
          <FormItem :label="$t('loginIndex.loginpasswordIn')" prop="passwordIn">
              <Input v-model.trim="formItem.passwordIn" type="password" />
          </FormItem>
          <FormItem :label="$t('loginIndex.loginpasswordNew')" prop="password">
              <Input v-model.trim="formItem.password" type="password" password/>
          </FormItem>
          <FormItem :label="$t('loginIndex.loginpwdCheck')" prop="pwdCheck">
              <Input v-model.trim="formItem.pwdCheck" type="password" password/>
          </FormItem>

          <FormItem>
					  <i-button class="submit" type="primary"  @click="handleSubmit('formItem')">{{ $t("devicesCreate.devCreateSubmit")}}</i-button>
				  </FormItem>
        </Form>
        <div slot="footer"></div>
    </Modal>

    <UserEdit
      v-if="ifCreate"
      @close="closeCreate"
    />
    <UserEdit
      v-if="ifUpdate"
      edit-type="update"
      :edit-item="editItem"
      @close="closeUpdate"
    />
  </div>
</template>

<script>
import {
  getList,
  delOta,
} from '@/api/user.js'
import {
  appUpdate,
} from '@/api/person.js'
import pageMixin from '@/utils/mixins/pageMixin.js'

import UserEdit from './UserEdit'
import UserListSettings from './UserListSettings'

export default {
  mixins: [
    pageMixin,
  ],
  components: {
    UserEdit,
  },
  computed: {
    btnShow () {
      return this.$store.state.btnShow
    },
  },
   watch: {
    btnShow(){
      this.columns = [
        // { type: 'selection' },
        {
          type: 'index',
          width: 60,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('permissionsIndex.UserName'),
          key: 'username',
        },
        {
          title: this.$t('permissionsIndex.roleTitle'),
          key: 'roleName',
        },
        {
          title: this.$t('permissionsIndex.accountType'),
          key: 'type',
          render: (h, { row }) => {
            let label = '-'
            if (row.type==0) {
              label =this.$t('permissionsIndex.companyAccount')
            }else if(row.type==1){
              label =this.$t('permissionsIndex.siteAccount')
            }
            return h('div', label)
          },
         
        },
        {
          title: this.$t('permissionsIndex.UserOld'),
          key: 'age',
        },
        {
          title: this.$t('permissionsIndex.UserRealName'),
          key: 'realName',
        },
        {
          title: this.$t('permissionsIndex.UserDeperName'),
          key: 'departName',
          render: (h, { row }) => {
            let label = '-'
            if (row.departName) {
              label = row.departName
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('permissionsIndex.UserEmail'),
          key: 'email',
          render: (h, { row }) => {
            let label = '-'
            if (row.email&&row.email!='null') {
              label = row.email
            }
            return h('div', label)
          },
        },
        // {
        //   title: '头像',
        //   key: 'downloadUrl',
        // },
        {
          title: this.$t('versionIndex.verOperation'),
          key: 'settings',
          width: 200,
          render: (h, { row }) => {
            return h(UserListSettings, {
              props: { row ,allPermissions:this.allPermissions},
              on: {
                itemClick: (name) => this.handleSettingsClick(name, row),
              },
            })
          },
        },
      ];
      return this.$store.state.btnShow
    }
  },

  data () {
    const pwdInValidate = (rule, value, callback) => {
      
      if (this.formItem.passwordIn == '') {
        callback(new Error(this.$t('loginIndex.loginpwdCheck3')));
      } else if(this.formItem.passwordIn.length<6){
        callback(new Error(this.$t('loginIndex.loginPhoneMin')));
      }
      else {
        callback()
      }
    }
    const pwdValidate = (rule, value, callback) => {
      if (this.formItem.password == '') {
        callback(new Error(this.$t('loginIndex.loginPassInput')));
      } else if(this.formItem.password.length<6){
        callback(new Error(this.$t('loginIndex.loginPhoneMin')));
      } 
      else {
        callback()
      }
      // this.$refs.formItem.validateField('pwdCheck')
      // callback()
    }
    const pwdCheckValidate = (rule, value, callback) => {
      if (this.formItem.password != '' && value == '') {
        callback(new Error(this.$t('loginIndex.loginpwdCheck1')))
      } else if (this.formItem.password != value) {
        callback(new Error(this.$t('loginIndex.loginpwdCheck2')))
      } else {
        callback()
      }
    }
    
    return {
      passName: '',
      passNameid: '',
      modal1: false,
      formItem: {
        passwordIn: '',
        password: '',
        pwdCheck: '',
        id: ''
     },
      validateRules: {
        passwordIn: [
            {required: true, validator: pwdInValidate, trigger: 'blur'}
        ],
        password: [
            {required: true, validator: pwdValidate, trigger: 'blur'}
        ],
        pwdCheck: [
            {required: true, validator: pwdCheckValidate, trigger: 'blur'}
        ]
      },
      selection: [],
      list: [],
      personName: '',
      personEmail: '',
      columns: [
        // { type: 'selection' },
        {
          type: 'index',
          width: 60,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('permissionsIndex.UserName'),
          key: 'username',
        },
        {
          title: this.$t('permissionsIndex.roleTitle'),
          key: 'roleName',
        },
        {
          title: this.$t('permissionsIndex.accountType'),
          key: 'type',
          render: (h, { row }) => {
            let label = '-'
            if (row.type==0) {
              label =this.$t('permissionsIndex.companyAccount')
            }else if(row.type==1){
              label =this.$t('permissionsIndex.siteAccount')
            }
            return h('div', label)
          },
         
        },
        {
          title: this.$t('permissionsIndex.UserOld'),
          key: 'age',
        },
        {
          title: this.$t('permissionsIndex.UserRealName'),
          key: 'realName',
        },
        {
          title: this.$t('permissionsIndex.UserDeperName'),
          key: 'departName',
          render: (h, { row }) => {
            let label = '-'
            if (row.departName) {
              label = row.departName
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('permissionsIndex.UserEmail'),
          key: 'email',
          render: (h, { row }) => {
            let label = '-'
            if (row.email&&row.email!='null') {
              label = row.email
            }
            return h('div', label)
          },
        },
        // {
        //   title: '头像',
        //   key: 'downloadUrl',
        // },
        {
          title: this.$t('versionIndex.verOperation'),
          key: 'settings',
          width: 200,
          render: (h, { row }) => {
            return h(UserListSettings, {
              props: { row ,allPermissions:this.allPermissions},
              on: {
                itemClick: (name) => this.handleSettingsClick(name, row),
              },
            })
          },
        },
      ],

      ifCreate: false,
      ifUpdate: false,
      editItem: null,
      allPermissions:{
        verAddBtn:false,
        verListSettingsEdit:false,
        verListSettingsDel:false,
        loginPhoneEdit:false,
      },
    }
  },

  mounted () {
    this.$_page_update()
    this.getAllPermissions()
  },

  methods: {
    getAllPermissions(){
      let da=JSON.parse(window.localStorage.getItem('logo'))||[]
      da.map(v => {
        if(v.permission=='#permissions'&&v.children){
          v.children.map(a=>{
            if(a.permission=='#UserTit'&&a.children){
              a.children.map(b=>{
              if(b.permission=='#verAddBtn'&&b.checked==='true'){
                this.allPermissions.verAddBtn=true
              }
              if(b.permission=='#verListSettingsEdit4'&&b.checked==='true'){
                this.allPermissions.verListSettingsEdit=true
              }
              if(b.permission=='#verListSettingsDel4'&&b.checked==='true'){
                this.allPermissions.verListSettingsDel=true
              }
              if(b.permission=='#loginPhoneEdit'&&b.checked==='true'){
                this.allPermissions.loginPhoneEdit=true
              }
            })} 
            
          })
        }
        
      });
    },
    showCreate () {
      this.ifCreate = true
    },
    closeCreate (ifUpdated) {
      ifUpdated && this.$_page_update()
      this.ifCreate = false
    },

    showUpdate (item) {
      this.ifUpdate = true
      this.editItem = item
    },
    closeUpdate (ifUpdated) {
      ifUpdated && this.$_page_update()
      this.ifUpdate = false
    },

    handleSelection (selection = []) {
      this.selection = selection
    },
    handleSelectionAllStatus (status) {
      this.$refs.table.selectAll(status)
    },

    handleSettingsClick (name, row) {
      switch (name) {
        case 'edit':
          this.showUpdate(row)
          break
        case 'del':
          this.handleDel(row)
          break
        case 'pass':
          this.handlePass(row)
          break
      }
    },
    handlePass (item) {
      console.log(item)
      this.passName = item.username
      this.passNameid = item.id
      this.modal1 = true
      this.$refs.formItem.resetFields()
    },
    handleSubmit (name) {
		  this.$refs[name].validate((valid) => {
        if (valid) {
          this.appUpdateClick()
        }else{
          
        }

      })
    },
    async appUpdateClick () {
      let that = this 
      let reg=/^[0-9]{6,12}$/
      if(reg.test(that.formItem.password)==false){
        this.$Message.error(this.$t('loginIndex.loginpwdCheck9'))
        return
      }else if(that.formItem.passwordIn==that.formItem.password){
        this.$Message.error(this.$t('loginIndex.loginpwdCheck10'))
        return
      }
      const { success, data } = await appUpdate ({
        username: that.passName,
        password: that.formItem.passwordIn,
        newPassWord: that.formItem.password,
      })
      if (success) {
        // console.log(data)
        if (data.code == 0) {
          that.modal1 = false
          that.$Message.success(this.$t('loginIndex.loginpwdCheck4'));
        }
      } else {
        this.$Message.error(this.$t('loginIndex.loginpasswordIn')+this.$t('loginIndex.loginpwdCheck5'));
      }
    },
    async getData (query) {
      const { success, data } = await getList({
        page: query.page,
        limit: query.pageSize,
        username: this.personName,
        email: this.personEmail
      })
      let list = []
      let page = 1
      let total = 0
      if (success) {
        list = data.data
        page = data.pageNum || 1
        total = data.count
      }
      this.list = list
      this.page = page
      this.pageSize = query.pageSize
      this.total = total
    },
    async handleDel (item) {
      this.$Modal.confirm({
        title: this.$t('permissionsIndex.UserDelN'),
        // content: this.$t('versionIndex.verDelAreaIs') + item.areaName + this.$t('versionIndex.verDelAreaIsN'),
        content: this.$t('permissionsIndex.UserDelIs'),
        onOk: async () => {
          const { success } = await delOta({ id: item.id })
          if (success) {
            this.$Message.success(this.$t('versionIndex.verDelBtnSucc'))
            this.$_page_update()
          } else {
            // this.$Message.error(this.$t('permissionsIndex.UserDelHint'))
            this.$Message.error(this.$t('newDevices.delUserTip'))
          }
        },
      })
    },
  },
}
</script>

<style lang="less" scoped>
.setting-area {
  .clearfix();

  .btns {
    float: right;
  }
  .title {
    line-height: @lh-base;
    font-size: 18px;
    font-weight: bold;
  }
}
</style>
